package top.blackr.folivora.common.security.crud.repository;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.repository.CrudRepository;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import top.blackr.folivora.common.security.crud.mapper.SysDeptRelationMapper;
import top.blackr.folivora.common.security.crud.model.entity.SysDept;
import top.blackr.folivora.common.security.crud.model.entity.SysDeptRelation;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class SysDeptRelationRepository extends CrudRepository<SysDeptRelationMapper, SysDeptRelation> {

    /**
     * 维护部门关系
     *
     * @param sysDept 部门
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertDeptRelation(SysDept sysDept) {
        // 增加部门关系表
        List<SysDeptRelation> relationList = this.list(Wrappers.<SysDeptRelation>lambdaQuery()
                        .eq(SysDeptRelation::getDescendant, sysDept.getParentId()))
                .stream().peek(relation -> relation.setDescendant(sysDept.getDeptId())).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(relationList)) {
            this.saveBatch(relationList, relationList.size());
        }

        // 自己也要维护到关系表中
        SysDeptRelation own = new SysDeptRelation();
        own.setDescendant(sysDept.getDeptId());
        own.setAncestor(sysDept.getDeptId());
        baseMapper.insert(own);
    }

    /**
     * 通过ID删除部门关系
     *
     * @param id 部门id
     */
    public void deleteAllDeptRelation(Integer id) {
        baseMapper.deleteDeptRelationsById(id);
    }

    /**
     * 更新部门关系
     *
     * @param relation 部门关系
     */
    public void updateDeptRelation(SysDeptRelation relation) {
        baseMapper.updateDeptRelations(relation);
    }

}
